<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CIBlog
 *
 * 使用codeigniter框架开发的一个博客。
 * 
 * @package     ciblog
 * @author      Eric
 * @copyright   Copyright (c) 2011 - 2012, Eric
 * @license     GNU General Public License 2.0
 * @link        http://www.hebaijun.com
 * @version     1.0
 */

 //----------------------------------------------------------

 /**
  * 取Tag的模型
  *
  * 
  *
  * @package     ciblog
  * @subpackage  Models
  * @category    Models
  * @author      Eric <baijun.he@163.com>
  * @link        http://www.hebaijun.com
  */
class Tag_m extends CI_Model {

	/**
     * 构造函数
     * 
     * @access public
     * @return void
     */
    public function __construct()
    {
		parent::__construct();
		
		log_message('debug', "CIBlog: Tag Model Class Initialized");

		//加载缓存适配器，如果memcached不支持 则用file类型缓存
		$this->load->driver('cache', array('adapter' => config_item('cache_adapter'), 'backup' => config_item('cache_backup')));
    }

	/**
     * 取得tag的信息
     * 
     * @access public
	 * @param array $param
     * @return mixed 取决于数据库保存的内容
     */
    public function get_tag( $result = '*',$param = array() )
    {
		//返回值
		$value = FALSE;
	
		$table_terms = $this->db->dbprefix('terms');
		$table_term_relationships = $this->db->dbprefix('term_relationships');
		$this->db->select($result);
		$this->db->from($table_terms);
		$this->db->where('term_taxonomy', 'post_tag');
		
		if( ! empty( $param ) )
		{
			//通过post_id取
			if(isset($param['post_id']) && ! empty($param['post_id']))
			{
				$this->db->join($table_term_relationships,"term_id = rel_term_id",'INNER');
				$this->db->where('rel_post_id', $param['post_id']);
			}

			//通过term_id取
			if(isset($param['term_id']) && ! empty($param['term_id']))
			{
				$this->db->where('term_id', $param['term_id']);
			}
		}
		$sql = $this->db->_compile_select();

		$key = md5('tag_'.$sql);
		$posts = $this->cache->get($key);
		if($value === FALSE)
		{
			$query = $this->db->get();
			$value = $query->result();
			$this->cache->save($key,$value,config_item('cache_expire'));
		}

		return $value;
    }

	/**
     * 取得所有的分类信息，做导航等用处
     * 
     * @access public
	 * @param string 需要取得的字段
     * @return array 所有自动加载的系统设置
     */
    public function load_all_tag($param = '*')
    {
		//返回值
		$all_tag = FALSE;

		$all_tag = $this->cache->get('all_tag');

		if($all_tag === FALSE)
		{
			$table_cat = $this->db->dbprefix('terms');
			$query = $this->db->query("SELECT $param FROM $table_cat WHERE term_taxonomy = 'post_tag'");
			if ($query->num_rows() > 0)
			{
				$all_tag = array();
				$all_tag = $query->result();
				$this->cache->save('all_tag',$all_tag,config_item('cache_expire'));
			}
		}

		return $all_tag;
    }	
}

/* End of file tag.php */
/* Location: ./application/models/tag.php */